package com.onstar.cn.common.error;

import android.text.TextUtils;

import com.onstar.cn.common.util.CommonUtil;

import org.json.JSONObject;

import java.io.Serializable;

public class CommErrorUtils implements Serializable {
	private static final long serialVersionUID = 1L;
	private static final String DEFAULT_ERROR_CODE="1904";
	private static final String DEFAULT_ERROR_MSG="Network exception.";
	private String errorCode;
	private String errorMsg;

	public CommErrorUtils() {
	}

	public CommErrorUtils(String errorCode, String errorMsg) {
		this.errorCode = errorCode;
		this.errorMsg = errorMsg;
	}

	public String getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(String errorCode) {
		this.errorCode = errorCode;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public static CommErrorUtils parseResponse(String json) throws Exception{
		CommErrorUtils entity = new CommErrorUtils();
		if(TextUtils.isEmpty(json) || json.startsWith("<"))
			return entity;
		try {
			JSONObject jsonObject = new JSONObject(json);
			if (jsonObject.has("error")) {
				if (!CommonUtil.isNull(jsonObject.getString("error")) && jsonObject.has("error_description")
						&& !CommonUtil.isNull(jsonObject.getString("error_description"))) {
					// 针对用户密码锁住情况下
					entity.setErrorCode("L7_" + jsonObject.getString("error"));
					entity.setErrorMsg(jsonObject.getString("error_description"));
				} else if (!CommonUtil.isNull(jsonObject.getString("error")) && !jsonObject.getString("error").contains("{")&& !jsonObject.has("error_description") && !jsonObject.has("description")) {
					entity.setErrorCode("L7_" + jsonObject.getString("error"));
					entity.setErrorMsg("");
				} else {
					JSONObject error = jsonObject.getJSONObject("error");
					if (error.has("code")) {
						entity.setErrorCode(error.getString("code"));
					}
					if (error.has("description")) {
						entity.setErrorMsg(error.getString("description"));
					}
				}
			} else {
				if (jsonObject.has("code")) {
					entity.setErrorCode(jsonObject.getString("code"));
				}
				if (jsonObject.has("description")) {
					entity.setErrorMsg(jsonObject.getString("description"));
				} else if (jsonObject.has("error_description")) {
					entity.setErrorMsg(jsonObject.getString("error_description"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return entity;
	}
	
	public static CommErrorUtils defaultError(){
		return new CommErrorUtils(DEFAULT_ERROR_CODE,DEFAULT_ERROR_MSG);
	}
	
}
